﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using System.Xml;

namespace Beyondsoft.Tuanju.DataManager.DealProviders
{
    //<url id="1">
    //    <loc>http://beijing.lashou.com/deal/833983.html</loc>
    //    <wap_url><![CDATA[http://m.lashou.com/detail.php?id=833983]]></wap_url>
    //    <data>
    //        <display>
    //            <website>拉手网</website>
    //            <cate>其他</cate>
    //            <siteurl>http://beijing.lashou.com/</siteurl>
    //            <city>北京</city>
    //            <gid>833983</gid>
    //            <title><![CDATA[仅售46元！市场价最高161元的九门轩百味馆双人火锅套餐一份：锅底（清汤锅/鸳鸯锅，2选1）+特色牛羊肉专拼+蔬菜拼盘（蒿子杆+土豆+萝卜+大白菜）+丸类拼盘（鱼丸+牛肉丸+鸡肉丸+虾丸）+宽粉+面条+小料（麻酱/香油蒜泥/海鲜料，3选2）+餐具！拉手券消费仅限10:30-17:00使用！传统美味，健康欢笑统统涮起来！]]></title>
    //            <image>http://s1.lashouimg.com/zt/201205/07/133639730333799400.jpg</image>
    //            <small_image>http://s2.lashouimg.com/zt_220/201205/07/133639730333799400.jpg</small_image>
    //            <startTime>1336406400</startTime>
    //            <endTime>1340121600</endTime>
    //            <value>161.00</value>
    //            <price>46.00</price>
    //            <rebate>2.9</rebate>
    //            <bought>38</bought>
    //            <detail><![CDATA[辣的激情，麻的诱惑，挑战你的味蕾极限！]]></detail>
    //            <shops>
    //                <shop>
    //                    <name><![CDATA[九门轩百味馆]]></name>
    //                    <tel><![CDATA[010-52438943]]></tel>
    //                    <addr><![CDATA[北京市西城区粮食店街17号（前门步行街）]]></addr>
    //                    <longitude>116.39770</longitude>
    //                    <latitude>39.89494</latitude>
    //                </shop>
    //            </shops>
    //        </display>
    //    </data>
    //</url>

    public class Lashou : DealProvider
    {
        private const string url = "http://open.client.lashou.com/api/detail/city/{0}/p/1/r/50";

        protected override string Name
        {
            get { return "lashou"; }
        }

        protected override string ApiAddress
        {
            get { return url; }
        }

        protected override async Task<IEnumerable<Deal>> FetchDeals(City city)
        {
            string destUrl = string.Format(url, city.CityName);

            Uri uri = new Uri(destUrl);

            List<Deal> deals = new List<Deal>();

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Async = true;

            XmlReader reader = XmlReader.Create(destUrl, settings);

            int index = 0;

            while (await reader.ReadAsync())
            {
                ++index;

                if (reader.ReadToFollowing("display"))
                {
                    string nodeXml = await reader.ReadOuterXmlAsync();
                    deals.Add(await Parse(nodeXml));
                }

                if (index > FetchCount)
                    break;
            }

            return deals;
        }

        private async Task<Deal> Parse(string xml)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(xml);

            var nodes = xdoc.ChildNodes;

            Deal deal = new Deal();

            foreach (var node in nodes)
            {
                deal.Website = node.SelectSingleNode("website").InnerText;
                deal.Gid = node.SelectSingleNode("gid").InnerText;
                deal.Title = node.SelectSingleNode("title").InnerText;

                string category = node.SelectSingleNode("cate").InnerText;
                deal.Category = await this.ConvertFrom(category);

                deal.Details = node.SelectSingleNode("detail").InnerText;
                deal.Price = double.Parse(node.SelectSingleNode("price").InnerText);
                deal.Value = double.Parse(node.SelectSingleNode("value").InnerText);
                deal.Bought = int.Parse(node.SelectSingleNode("bought").InnerText);
                deal.Image = node.SelectSingleNode("image").InnerText;
                deal.StartTime = long.Parse(node.SelectSingleNode("startTime").InnerText).ToDateTime();
                deal.EndTime = long.Parse(node.SelectSingleNode("endTime").InnerText).ToDateTime();

                deal.Discount = deal.Value == 0 ? 0 : Math.Ceiling(deal.Price / deal.Value * 100);
                deal.UriLink = node.SelectSingleNode("siteurl").InnerText + "deal/" + deal.Gid + ".html";
                deal.ExpireTime = (deal.EndTime - DateTime.Today).Days;
            }

            return deal;
        }
    }
}
